import { login } from '@/api/login'
import { _setToken, _getToken } from '@/util/token'

const authentication = {
    state: {
        token: _getToken(),
        username: '',
        avatar: '',
        postions: [],
        authority: []
    },
    mutations: {
        _s_user: (state, userInfo) => {
                state.token = userInfo.token
                state.username = userInfo.name
                state.avatar = userInfo.avatar
                state.postions = userInfo.postions
                state.authority = userInfo.authority
            }
            // _s_token: (state, token) => {
            //     state.token = token
            // },
            // _s_username: (state, username) => {
            //     state.username = username
            // },
            // _s_avatar: (state, avatar) => {
            //     state.avatar = avatar
            // },
            // _s_postions: (state, postions) => {
            //     state.postions = postions
            // },
            // _s_authority: (state, authority) => {
            //     state.authority = authority
            // }
    },
    actions: {
        doLogin({ commit, dispatch }, _params) {
            return new Promise((resolve, reject) => {
                login(_params)
                    .then((res) => {
                        const tokenStr = `Bearer ${res.data.token}`
                        _setToken(tokenStr)
                        console.log('进入 authentication ...')
                        console.log(res.data)
                        commit('_s_user', res.data)
                        resolve(res)
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        }
    }
}

export default authentication
